# ocr.py
import base64
import json
import requests
from urllib.parse import urlencode, urlparse
from datetime import datetime
from time import mktime
from wsgiref.handlers import format_date_time

from config import SPARK_APPID, SPARK_APIKey, SPARK_APISecret, OCR_URL


def assemble_url(request_url, method="POST"):
    """生成带鉴权的 URL"""
    u = urlparse(request_url)
    host, path = u.hostname, u.path
    date = format_date_time(mktime(datetime.now().timetuple()))
    signature_str = f"host: {host}\ndate: {date}\n{method} {path} HTTP/1.1"
    sign = hmac_sha256(signature_str, SPARK_APISecret)
    authorization = encode_auth_string(SPARK_APIKey, signature_str, sign)
    return f"{request_url}?{urlencode({'host': host, 'date': date, 'authorization': authorization})}"


def hmac_sha256(data, secret):
    """生成 HMAC-SHA256 签名并返回 base64 编码"""
    import hmac
    import hashlib
    return base64.b64encode(
        hmac.new(secret.encode(), data.encode(), digestmod=hashlib.sha256).digest()
    ).decode()


def encode_auth_string(apikey, signature_str, signature):
    """生成授权头字符串并 base64 编码"""
    auth_str = (
        f'api_key="{apikey}", algorithm="hmac-sha256", '
        f'headers="host date request-line", signature="{signature}"'
    )
    return base64.b64encode(auth_str.encode()).decode()


def get_resume_text(image_path: str) -> str:
    """将简历图片中的文字提取为字符串"""
    with open(image_path, "rb") as f:
        image_bytes = f.read()

    body = {
        "header": {"app_id": SPARK_APPID, "status": 3},
        "parameter": {
            "sf8e6aca1": {
                "category": "ch_en_public_cloud",
                "result": {"encoding": "utf8", "compress": "raw", "format": "json"}
            }
        },
        "payload": {
            "sf8e6aca1_data_1": {
                "encoding": "jpg",
                "image": base64.b64encode(image_bytes).decode('utf-8'),
                "status": 3
            }
        }
    }

    headers = {
        "content-type": "application/json",
        "host": "api.xf-yun.com",
        "app_id": SPARK_APPID
    }

    response = requests.post(assemble_url(OCR_URL), data=json.dumps(body), headers=headers)
    resp_json = response.json()

    try:
        encoded_text = resp_json['payload']['result']['text']
        decoded_text = base64.b64decode(encoded_text).decode()
        text_json = json.loads(decoded_text)
        return ''.join(
            w['content']
            for p in text_json.get('pages', [])
            for l in p.get('lines', [])
            if 'words' in l
            for w in l['words']
        )
    except Exception as e:
        print("❌ OCR解析失败:", e)
        return ""
